package com.ruoyi.project.system.HeadFigure.Controller;


import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.HeadFigure.domain.HP;
import com.ruoyi.project.system.HeadFigure.service.hphotosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

import static com.ruoyi.common.utils.PageUtils.startPage;

@RestController
@RequestMapping("/hphotos")
public class HPhotosController extends BaseController {
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private hphotosService hs;

    private HP hp = new HP();

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            System.out.println("ajx==>"+ajax);
            //将信息写入数据库
            hp.setUrl(url);
            hp.setFileName(fileName);

            hs.save(hp);
            System.out.println(hp);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    @GetMapping
    public TableDataInfo getall(){
        startPage();
        List<HP> hl = hs.getall();

        return getDataTable(hl);
    }


}
